package com.seafood.controller;

import com.seafood.common.PageResult;
import com.seafood.common.Result;
import com.seafood.dto.CategoryDTO;
import com.seafood.service.CategoryService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 分类控制器
 */
@Tag(name = "分类管理", description = "产品分类相关API")
@RestController
@RequestMapping("/categories")
@RequiredArgsConstructor
@Validated
public class CategoryController {
    
    private final CategoryService categoryService;
    
    /**
     * 获取所有顶级分类
     */
    @Operation(summary = "获取顶级分类", description = "获取所有顶级分类列表")
    @GetMapping("/top")
    public Result<List<CategoryDTO>> getTopCategories() {
        try {
            List<CategoryDTO> categories = categoryService.getTopCategories();
            return Result.success(categories);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 获取分类树（包含子分类）
     */
    @Operation(summary = "获取分类树", description = "获取完整的分类树结构")
    @GetMapping("/tree")
    public Result<List<CategoryDTO>> getCategoriesTree() {
        try {
            List<CategoryDTO> categories = categoryService.getAllCategoriesTree();
            return Result.success(categories);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 根据父分类ID获取子分类
     */
    @Operation(summary = "获取子分类", description = "根据父分类ID获取子分类列表")
    @GetMapping("/parent/{parentId}")
    public Result<List<CategoryDTO>> getCategoriesByParent(@PathVariable Long parentId) {
        try {
            List<CategoryDTO> categories = categoryService.getCategoriesByParentId(parentId);
            return Result.success(categories);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 根据ID获取分类详情
     */
    @Operation(summary = "获取分类详情", description = "根据分类ID获取详细信息")
    @GetMapping("/{id}")
    public Result<CategoryDTO> getCategoryById(@PathVariable Long id) {
        try {
            CategoryDTO category = categoryService.getCategoryById(id);
            return Result.success(category);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 搜索分类
     */
    @Operation(summary = "搜索分类", description = "根据名称模糊搜索分类")
    @GetMapping("/search")
    public Result<List<CategoryDTO>> searchCategories(@RequestParam String name) {
        try {
            List<CategoryDTO> categories = categoryService.searchCategoriesByName(name);
            return Result.success(categories);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 创建分类
     */
    @Operation(summary = "创建分类", description = "创建新的产品分类")
    @PostMapping
    @PreAuthorize("hasRole('ADMIN')")
    public Result<CategoryDTO> createCategory(@Valid @RequestBody CategoryDTO categoryDTO) {
        try {
            CategoryDTO createdCategory = categoryService.createCategory(categoryDTO);
            return Result.success("分类创建成功", createdCategory);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 更新分类
     */
    @Operation(summary = "更新分类", description = "更新分类信息")
    @PutMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<CategoryDTO> updateCategory(@PathVariable Long id, 
                                            @Valid @RequestBody CategoryDTO categoryDTO) {
        try {
            CategoryDTO updatedCategory = categoryService.updateCategory(id, categoryDTO);
            return Result.success("分类更新成功", updatedCategory);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
    
    /**
     * 删除分类
     */
    @Operation(summary = "删除分类", description = "删除指定分类")
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public Result<Void> deleteCategory(@PathVariable Long id) {
        try {
            categoryService.deleteCategory(id);
            return Result.success("分类删除成功", null);
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        }
    }
}